#include "defectdatatcpclient.h"
#include <QDateTime>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonDocument>
DefectDataTcpClient::DefectDataTcpClient(QObject *parent)
    : QObject{parent},retryCount(0),maxRetry(30)
{
    socket = new QTcpSocket(this);
    reconnectTimer = new QTimer(this);
    reconnectTimer->setInterval(10000);

    //当链接失败时进行重连操作
    connect(reconnectTimer,&QTimer::timeout,this,&DefectDataTcpClient::tryConnect);

    //连接成功后的处理
    connect(socket,&QTcpSocket::connected,this,&DefectDataTcpClient::onConnected);

    connect(socket,&QTcpSocket::disconnected,this,&DefectDataTcpClient::onDisConnected);



}

void DefectDataTcpClient::tryConnect()
{
    if(retryCount >= maxRetry){
        qDebug()<<"重连次数过多,退出链接";
        reconnectTimer->stop();
        return;
    }
    if(socket->state() == QAbstractSocket::UnconnectedState){
        qDebug()<<"正在尝试第"<<(retryCount+1)<<"次链接....";
        socket->abort();//断开之前的链接
        socket->connectToHost(host,port);
        retryCount++;
    }
}

void DefectDataTcpClient::onConnected()
{
    qDebug()<<"链接成功";
    reconnectTimer->stop();
}

void DefectDataTcpClient::onDisConnected()
{
    qDebug()<<"与服务器断开链接...尝试重新链接。。。";
    reconnectTimer->start();

}

void DefectDataTcpClient::startConnection(const QString &host, quint16 port)
{
    this->host = host;
    this->port = port;
    retryCount = 0;
    reconnectTimer->start();
}

QString DefectDataTcpClient::ConvertJsonToStr(const QJsonObject &jsonObject)
{
    QString xml;
    /*
    //auto DefectListArr = jsonObject["DefectList"].toArray();

    //xml += QDateTime::currentDateTime().toString("yyyyMMddhhmmss");
    xml += "B1T812";
    xml += "D";

    //定义缺陷数据的发送格式
    QString tempDataFormat1 = R"(<?xml version='1.0' encoding='utf-8' standalone='no'?><table><rowCount>1</rowCount><headCount>11</headCount><head><h1>标志位</h1><h2>缺陷名称</h2><h3>缺陷等级</h3><h4>缺陷宽度</h4><h5>缺陷高度</h5> <h6>面积</h6><h7>距头</h7><h8>距尾</h8><h9>距左</h9><h10>距右</h10><h11>预留号</h11></head><body><r1><r1c1>1</r1c1> <r1c2>%1</r1c2><r1c3>%2</r1c3><r1c4> </r1c4><r1c5> </r1c5><r1c6> </r1c6><r1c7></r1c7><r1c8> </r1c8><r1c9> </r1c9><r1c10> </r1c10><r1c11>%3</r1c11> </r1>)";
    QString msgSteelBody = tempDataFormat1.arg(jsonObject["SteelName"].toString().toUtf8())
                        .arg(jsonObject["Level"].toInt())
                        .arg(jsonObject["SteelNo"].toInt());


    //处理缺陷信息格式
    for (int i = 0; i < DefectListArr.size(); ++i) {
        QJsonObject defect = DefectListArr.at(i).toObject();
        QString str = R"(<r%1><r%1c1>0</r%1c1><r%1c2>%2</r%1c2><r%1c3>%3</r%1c3><r%1c4>%4</r%1c4><r%1c5>%5</r%1c5><r%1c6>%6</r%1c6><r%1c7>%7</r%1c7><r%1c8>%8</r%1c8><r%1c9>%9</r%1c9><r%1c10>%10</r%1c10><r%1c11>%11</r%1c11></r%1>)";
        QString msgDefectBody =str.arg( (i+2) )
                        .arg(defect["DefectName"].toString().toUtf8())
                        .arg(defect["defectLevel"].toInt())
                        .arg(defect["width"].toInt())
                        .arg(defect["height"].toInt())
                        .arg(defect["Area"].toInt())
                        .arg(defect["TopinSteel"].toInt())
                        .arg(defect["BottomInSteel"].toInt())
                        .arg(defect["LeftinSteel"].toInt())
                        .arg(defect["RightinSteel"].toInt())
                        .arg(1);
        msgSteelBody.append(msgDefectBody);
    }

    QString XmlTail = R"(</body></table>

    )";

    msgSteelBody.append(XmlTail);
    xml += msgSteelBody;
    //获取整体的数据包大小

    xml.prepend(QString("%1").arg(xml.length()+6,6,10,QLatin1Char('0')));
*/
    xml += "000000";
    xml += "B1T812";
    xml += "D";
    QJsonDocument jsonDoc(jsonObject);
    QByteArray jsonByteArray = jsonDoc.toJson(QJsonDocument::Compact);
    xml += jsonByteArray;
    xml += "\n";

    // 计算完整的数据包大小（包含头部占位）
    int PackAgeSize = xml.toUtf8().size();

    QString header = QString("%1").arg(PackAgeSize,6,10,QLatin1Char('0'));
    xml.replace(0, 6, header);
    qDebug()<<"发送的数据大小: "<<PackAgeSize;

    return xml;
}

void DefectDataTcpClient::SendData(const QJsonObject &jsonObject)
{
    if(!socket->isOpen() || socket->state() != QAbstractSocket::ConnectedState){
        return;
    }

    QString resData = ConvertJsonToStr(jsonObject);
    socket->write(resData.toUtf8());
    socket->flush();
}




